#include "NavigationWidget.h"
#include <QApplication>
#include <QPainter>
#include <QPainterPath>
#include <QDebug>
#include <QScrollBar>
#include <QFont>
#include <QHeaderView>
#include <QMouseEvent>
#include <QStyledItemDelegate>
#include <QStyleOption>
#include <QStyle>

const QString NavigationWidget::stove_COLOR = "#588EBD";
const QString NavigationWidget::PAGE_COLOR = "#BCD7FF";
const QString NavigationWidget::SELECTED_COLOR = "#45BFFF";
const QString NavigationWidget::HOVER_COLOR = "rgba(69, 191, 255, 0.3)";

ArrowItemDelegate::ArrowItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

ArrowItemDelegate::~ArrowItemDelegate()
{
}

void ArrowItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
            const QModelIndex &index) const
{
    QString itemType = index.data(Qt::UserRole).toString();
    bool isStove = (itemType == "stove");
    bool isPage = (itemType == "page");
    
    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);
    
    if (isStove) {
        opt.font = QFont("Microsoft YaHei", 16, QFont::Bold);
        opt.palette.setColor(QPalette::Text, QColor("#588EBD"));
        opt.rect.setLeft(0);
    } else if (isPage) {
        opt.font = QFont("Microsoft YaHei", 16, QFont::Bold);
        opt.palette.setColor(QPalette::Text, QColor("#BCD7FF"));
        opt.rect.setLeft(0);
    }
    
    // 判断是否是第一个item
    bool isFirstItem = (index.row() == 0 && !index.parent().isValid());
    
    // 绘制背景
    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);
    
    if (isStove) {
        QColor bgColor = QColor("#0A1B34");
        opt.palette.setColor(QPalette::Text, QColor("#588EBD"));
        
        // 所有item都使用矩形背景，无圆角
        painter->fillRect(opt.rect, bgColor);
    } else if (isPage) {
        QColor bgColor;
        if (opt.state & QStyle::State_Selected) {
            bgColor = QColor("#007AED");
            opt.palette.setColor(QPalette::Text, QColor("#FFFFFF"));
        } else {
            bgColor = QColor("#27436B");
            opt.palette.setColor(QPalette::Text, QColor("#588EBD"));
        }
        painter->fillRect(opt.rect, bgColor);
    }
    
    painter->restore();
    
    // 绘制文本
    QFont font = opt.font;
    font.setPixelSize(16);
    painter->setFont(font);
    QPen pen = opt.palette.color(QPalette::Text);
    painter->setPen(pen);
    QRect textRect = opt.rect;
    if (isStove) {
        textRect.setLeft(24);
    } else if (isPage) {
        textRect.setLeft(32);
    }
    painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, opt.text);
    
    // 绘制箭头
    if (isStove && index.model()->hasChildren(index)) {
        QPixmap arrowPixmap;
        const QTreeView* view = qobject_cast<const QTreeView*>(option.widget);
        bool isExpanded = view && view->isExpanded(index);
        
        if (isExpanded) {
            arrowPixmap.load(":/img/images/icon-arrow03.png");
        } else {
            arrowPixmap.load(":/img/images/icon-arrow03.png");
        }
        
        if (!arrowPixmap.isNull()) {
            QRect iconRect(option.rect.right() - 16 - 12,
                          option.rect.center().y() - 5,
                          16, 10);
            painter->drawPixmap(iconRect, arrowPixmap);
        }
    }
}

NavigationWidget::NavigationWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_scrollArea(nullptr)
    , m_navigationTree(nullptr)
    , m_currentstove("")
    , m_currentPage("")
{
    setupUI();
    setupConnections();
}

NavigationWidget::~NavigationWidget()
{
}

void NavigationWidget::setupUI()
{
    setObjectName("navigationWidget");
    
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(2, 2, 2, 2);
    m_mainLayout->setSpacing(0);
    
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setObjectName("navigationScrollArea");
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    
    m_navigationTree = new QTreeWidget();
    m_navigationTree->setObjectName("navigationTree");
    m_navigationTree->setHeaderHidden(true);
    m_navigationTree->setRootIsDecorated(true);
    m_navigationTree->setItemsExpandable(true);
    m_navigationTree->setIndentation(0);
    m_navigationTree->setItemDelegate(new ArrowItemDelegate(m_navigationTree));
    
    m_scrollArea->setWidget(m_navigationTree);
    
    m_mainLayout->addWidget(m_scrollArea);
    
    // 模拟数据
    addstove("一号转炉");
    addstove("二号转炉");
    addstove("三号转炉");
    addstove("四号转炉");
    addstove("五号转炉");
    addstove("六号转炉");
    if (m_navigationTree->topLevelItemCount() > 0) {
        m_navigationTree->topLevelItem(0)->setExpanded(true);
        setSelectedItem("一号转炉", "主操作界面");
    }
}

void NavigationWidget::setupConnections()
{
    connect(m_navigationTree, &QTreeWidget::itemClicked, this, &NavigationWidget::onNavigationItemClicked);
    connect(m_navigationTree, &QTreeWidget::itemExpanded, this, &NavigationWidget::onItemExpanded);
    connect(m_navigationTree, &QTreeWidget::itemCollapsed, this, &NavigationWidget::onItemCollapsed);
}

void NavigationWidget::addstove(const QString &stoveName)
{
    createstoveItem(stoveName);
}

void NavigationWidget::createstoveItem(const QString &stoveName)
{
    QTreeWidgetItem *stoveItem = new QTreeWidgetItem(m_navigationTree);
    stoveItem->setText(0, stoveName);
    stoveItem->setData(0, Qt::UserRole, "stove");
    stoveItem->setData(0, Qt::UserRole + 1, stoveName);
    
    // 设置炉子样式
    stoveItem->setFont(0, QFont("Microsoft YaHei", 16, QFont::Bold));
    stoveItem->setForeground(0, QColor(stove_COLOR));
    stoveItem->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
    
    // 炉子不可被选中，只能展开/收缩
    stoveItem->setFlags(stoveItem->flags() & ~Qt::ItemIsSelectable);
    
    // 创建三个子页面
    createPageItem(stoveItem, "冶炼配置界面");
    createPageItem(stoveItem, "主操作界面");
    createPageItem(stoveItem, "冶炼追溯界面");
}

void NavigationWidget::createPageItem(QTreeWidgetItem *parent, const QString &pageName)
{
    QTreeWidgetItem *pageItem = new QTreeWidgetItem(parent);
    pageItem->setText(0, pageName);
    pageItem->setData(0, Qt::UserRole, "page");
    pageItem->setData(0, Qt::UserRole + 1, pageName);
    pageItem->setData(0, Qt::UserRole + 2, parent->text(0)); // 父炉子名称
    
    // 设置页面样式
    pageItem->setFont(0, QFont("Microsoft YaHei", 14, QFont::Normal));
    pageItem->setForeground(0, QColor(PAGE_COLOR));
    pageItem->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicator);
}

void NavigationWidget::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    
    QWidget::paintEvent(event);
}

void NavigationWidget::mousePressEvent(QMouseEvent *event)
{
    // 获取鼠标点击位置的项目
    QTreeWidgetItem *item = m_navigationTree->itemAt(event->pos());
    
    if (item) {
        QString itemType = item->data(0, Qt::UserRole).toString();
        
        if (itemType == "stove") {
            // 如果是炉子，完全阻止默认行为，包括清除选中状态
            // 直接调用我们的点击处理逻辑
            onNavigationItemClicked(item, 0);
            return; // 不调用父类的mousePressEvent，防止清除选中状态
        }
    }
    
    // 对于页面项目，使用默认行为
    QWidget::mousePressEvent(event);
}

void NavigationWidget::onNavigationItemClicked(QTreeWidgetItem *item, int column)
{
    QString itemType = item->data(0, Qt::UserRole).toString();
    QString itemText = item->data(0, Qt::UserRole + 1).toString();
    
    if (itemType == "page") {
        QString stoveName = item->data(0, Qt::UserRole + 2).toString();
        
        // 更新当前选中状态
        m_currentstove = stoveName;
        m_currentPage = itemText;
        
        // 清除其他项目的选中状态
        QTreeWidgetItemIterator it(m_navigationTree);
        while (*it) {
            (*it)->setSelected(false);
            ++it;
        }
        
        // 选中当前项目
        item->setSelected(true);
        
        qDebug() << "Page clicked:" << stoveName << "-" << itemText;
        
        // 发送索引信号
        int stoveIndex = -1;
        int pageIndex = -1;
        
        // 找到炉子索引
        for (int i = 0; i < m_navigationTree->topLevelItemCount(); ++i) {
            QTreeWidgetItem *stoveItem = m_navigationTree->topLevelItem(i);
            if (stoveItem && stoveItem->text(0) == stoveName) {
                stoveIndex = i;
                
                // 找到页面索引
                for (int j = 0; j < stoveItem->childCount(); ++j) {
                    QTreeWidgetItem *pageItem = stoveItem->child(j);
                    if (pageItem && pageItem->text(0) == itemText) {
                        pageIndex = j;
                        break;
                    }
                }
                break;
            }
        }
        
        if (stoveIndex >= 0 && pageIndex >= 0) {
            emit navigationItemClickedByIndex(stoveIndex, pageIndex);
        }
    } else if (itemType == "stove") {
        // 点击炉子时展开/折叠，炉子不允许被选中，不影响任何二级目录的选中状态
        // 先保存当前选中的二级目录状态
        QString currentSelectedStove = m_currentstove;
        QString currentSelectedPage = m_currentPage;
        QTreeWidgetItem *selectedPageItem = nullptr;
        
        // 先找到当前选中的页面项目
        if (!currentSelectedStove.isEmpty() && !currentSelectedPage.isEmpty()) {
            for (int i = 0; i < m_navigationTree->topLevelItemCount(); ++i) {
                QTreeWidgetItem *stoveItem = m_navigationTree->topLevelItem(i);
                if (stoveItem && stoveItem->text(0) == currentSelectedStove) {
                    for (int j = 0; j < stoveItem->childCount(); ++j) {
                        QTreeWidgetItem *pageItem = stoveItem->child(j);
                        if (pageItem && pageItem->text(0) == currentSelectedPage) {
                            selectedPageItem = pageItem;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        
        // 暂时禁用更新以减少闪烁
        m_navigationTree->setUpdatesEnabled(false);
        
        // 执行展开/折叠操作
        if (item->isExpanded()) {
            item->setExpanded(false);
        } else {
            item->setExpanded(true);
            emit stoveExpanded(itemText);
        }
        
        // 立即恢复选中状态，避免闪烁
        if (selectedPageItem) {
            selectedPageItem->setSelected(true);
        }
        
        // 重新启用更新
        m_navigationTree->setUpdatesEnabled(true);
    }
}

void NavigationWidget::onItemExpanded(QTreeWidgetItem *item)
{
    QString itemType = item->data(0, Qt::UserRole).toString();
    if (itemType == "stove") {
        QString stoveName = item->data(0, Qt::UserRole + 1).toString();
        qDebug() << "stove expanded:" << stoveName;
        emit stoveExpanded(stoveName);
    }
}

void NavigationWidget::onItemCollapsed(QTreeWidgetItem *item)
{
    QString itemType = item->data(0, Qt::UserRole).toString();
    if (itemType == "stove") {
        QString stoveName = item->data(0, Qt::UserRole + 1).toString();
        qDebug() << "stove collapsed:" << stoveName;
    }
}

void NavigationWidget::setSelectedItem(const QString &stoveName, const QString &pageName)
{
    QTreeWidgetItem *stoveItem = findstoveItem(stoveName);
    if (!stoveItem) return;
    
    // 展开炉子
    stoveItem->setExpanded(true);
    
    if (!pageName.isEmpty()) {
        // 查找指定的页面
        for (int i = 0; i < stoveItem->childCount(); ++i) {
            QTreeWidgetItem *pageItem = stoveItem->child(i);
            if (pageItem && pageItem->text(0) == pageName) {
                // 清除其他项目的选中状态
                QTreeWidgetItemIterator it(m_navigationTree);
                while (*it) {
                    (*it)->setSelected(false);
                    ++it;
                }
                
                // 选中指定页面
                pageItem->setSelected(true);
                
                // 更新当前选中状态
                m_currentstove = stoveName;
                m_currentPage = pageName;
                
                break;
            }
        }
    }
}

void NavigationWidget::setSelectedItemByIndex(int stoveIndex, int pageIndex)
{
    // 检查炉子索引是否有效
    if (stoveIndex < 0 || stoveIndex >= m_navigationTree->topLevelItemCount()) {
        qWarning() << "NavigationWidget::setSelectedItemByIndex: Invalid stove index:" << stoveIndex;
        return;
    }
    
    QTreeWidgetItem *stoveItem = m_navigationTree->topLevelItem(stoveIndex);
    if (!stoveItem) return;
    
    // 展开炉子
    stoveItem->setExpanded(true);
    
    // 检查页面索引是否有效
    if (pageIndex >= 0 && pageIndex < stoveItem->childCount()) {
        QTreeWidgetItem *pageItem = stoveItem->child(pageIndex);
        if (pageItem) {
            // 清除其他项目的选中状态
            QTreeWidgetItemIterator it(m_navigationTree);
            while (*it) {
                (*it)->setSelected(false);
                ++it;
            }
            
            // 选中指定页面
            pageItem->setSelected(true);
            
            // 更新当前选中状态
            m_currentstove = stoveItem->text(0);
            m_currentPage = pageItem->text(0);
            
            // 滚动到选中项目
            m_navigationTree->scrollToItem(pageItem);
            
            // 发送索引信号
            emit navigationItemClickedByIndex(stoveIndex, pageIndex);
        }
    } else {
        // 炉子不可被选中，只展开炉子，不选中任何项目
        // 清除所有项目的选中状态
        QTreeWidgetItemIterator it(m_navigationTree);
        while (*it) {
            (*it)->setSelected(false);
            ++it;
        }
        
        // 不选中炉子，只展开
        m_currentstove = "";
        m_currentPage = "";
        
        // 滚动到炉子项目（但不选中）
        m_navigationTree->scrollToItem(stoveItem);
    }
}

QTreeWidgetItem* NavigationWidget::findstoveItem(const QString &stoveName)
{
    for (int i = 0; i < m_navigationTree->topLevelItemCount(); ++i) {
        QTreeWidgetItem *item = m_navigationTree->topLevelItem(i);
        if (item && item->text(0) == stoveName) {
            return item;
        }
    }
    return nullptr;
}

void NavigationWidget::clearNavigationItems()
{
    m_navigationTree->clear();
    m_currentstove = "";
    m_currentPage = "";
}

QString NavigationWidget::getCurrentstove() const
{
    return m_currentstove;
}

QString NavigationWidget::getCurrentPage() const
{
    return m_currentPage;
}
